//
//  CRLoginController.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRLoginController.h"
#import "CRRegisterController.h"
#import "CRLoginModel.h"
#import "CRLoginView.h"
#import "CRTabBarViewController.h"
#import "MyKeyChainHelper.h"
#import "CRUserManager.h"
#import "CRResetPasswordController.h"
@interface CRLoginController ()
@property (nonatomic, strong) CRLoginView *loginView;
@property (nonatomic, strong) CRLoginModel *loginModel;

@property (nonatomic, assign) BOOL isSavePwd;

@end

@implementation CRLoginController

- (void)loadView
{
    [super loadView];
    self.loginView = [[CRLoginView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.loginView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layoutView];
    [self layoutData];
}

/**
 *  界面展示
 */
- (void)layoutView
{
    self.loginModel = [CRLoginModel new];
    self.loginView.loginModel = self.loginModel;
    
    [self.loginView.loginButton addTarget:self action:@selector(clickLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView.setUserButton addTarget:self action:@selector(clickSetNewUserButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView.forgetPButton addTarget:self action:@selector(clickforgetPasswordButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView.rememberPButton addTarget:self action:@selector(clickRememberPasswordButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginView.autoLButton addTarget:self action:@selector(clickAutoLoginButton:) forControlEvents:UIControlEventTouchUpInside];
    
}
/**
 *  数据
 */
- (void)layoutData
{
//    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
//    
//    
//    NSLog(@"%@", path);
    
    BOOL isSavePwd = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSavePwd"];
    BOOL isAutoLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isAutoLogin"];
    // 立即执行存入操作
    [[NSUserDefaults standardUserDefaults] synchronize];
    if (isSavePwd) {
        self.loginView.rememberPButton.selected = YES;
        
        // 从keyChain内取出用户名和密码 赋值给textField
        self.loginView.userText.text = [MyKeyChainHelper getUserNameWithService:KEY_USERNAME];
        self.loginView.passwordText.text = [MyKeyChainHelper getPasswordWithService:KEY_PASSWORD];
    }
    
    if (isAutoLogin) {
        self.loginView.autoLButton.selected = YES;
        [self clickLoginButton:self.loginView.loginButton];
        
    }
    
}

#pragma mark >>>> 点击事件

/**
 *  点击自动登录按钮事件
 *
*/
- (void)clickAutoLoginButton:(UIButton *)button
{
    button.selected = !button.selected;
    
    if (button.selected) {
        // 把自动登录写到沙盒中
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isAutoLogin"];
    } else {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isAutoLogin"];
    }
#warning   记住密码与自动登录未关联
//    点击自动登录，会自动选中记住密码；取消自动登录时，仍然记住密码状态
//    if (self.loginView.autoLButton.selected == YES) {
////        self.loginView.rememberPButton.selected = YES;
//        [self clickRememberPasswordButton:self.loginView.rememberPButton];
//    }
}

/**
 *  点击记住密码按钮事件
 *
 */
- (void)clickRememberPasswordButton:(UIButton *)button
{
    button.selected = !button.selected;
    
    if (button.selected) {
        _isSavePwd = YES;
        // 把记住密码写到沙盒中
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isSavePwd"];
        [MyKeyChainHelper deleteWithUserNameService:KEY_USERNAME psaawordService:KEY_PASSWORD];
    } else {
        _isSavePwd = NO;
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isSavePwd"];
    }
    
    // 点击取消密码时 会连带取消自动登录
//    if (self.loginView.rememberPButton.selected == NO) {
////        self.loginView.autoLButton.selected = NO;
//        [self clickAutoLoginButton:self.loginView.autoLButton];
//    }
}
/**
 *  点击注册按钮事件
 *
 */
- (void)clickSetNewUserButton:(UIButton *)button
{
    CRRegisterController *registerVC = [[CRRegisterController alloc] init];
    [self presentViewController:registerVC animated:YES completion:^{
    }];
}

/**
 *  点击忘记密码按钮事件(此处应该跳转到邮箱)
 *
 */
- (void)clickforgetPasswordButton:(UIButton *)button
{
    CRResetPasswordController *resetPwdVC = [[CRResetPasswordController alloc] init];
    resetPwdVC.isResetByPhone = YES;
    [self showViewController:resetPwdVC sender:nil];
    
}

/**
 *  点击登录按钮事件
 *
 */
- (void)clickLoginButton:(UIButton *)button
{
    NSString *userName = self.loginView.userText.text;
    NSString *password = self.loginView.passwordText.text;
    
    if ([userName isEqualToString:@""] || [password isEqualToString:@""]) {
       
        [self showAlertControllerWithTitle:@"登录失败" message:@"请检查，是或否填写完整"];
        return;
    }
//    NSLog(@"name:%@  pass:%@", userName, password);
    
    CRUserManager *manager = [CRUserManager defaultManager];
    [manager loginWithUsername:userName password:password success:^{ // 登录成功
    
//         判断是否记住密码
        if (_isSavePwd) {
            [MyKeyChainHelper saveUserName:userName userNameService:KEY_USERNAME psaaword:password psaawordService:KEY_PASSWORD];
        }
//         设置跳转到tabBarController
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        window.rootViewController = [window getSideViewController];
        
    } failure:^(NSError *error) { // 登录失败
        
        [self showAlertControllerWithTitle:@"登录失败" message:@"账号或者密码错误，请重新输入"];
        
    }];
}

#pragma mark >>>> 展示提醒信息
- (void)showAlertControllerWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];

    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:cancleAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


@end
